package org.bing.engine.utility.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileHelper {

    public static void writeUrlToFile(String url, String file) {
        File f = new File(file);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        UrlHelper.readToFile(url, file);
    }

    public static void write(String txt, String file) {
        File f = new File(file);
        f.getParentFile().mkdirs();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(txt.getBytes("UTF-8"));
        } catch (Exception e) {
            f.delete();
            throw new RuntimeException(e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    fos = null;
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /** resoleve '/' to '\' problem (win) */
    public static String fixPathToNative(String path) {
        if (!File.separator.equals("/")) {
            StringBuilder sb = new StringBuilder(path.length());
            for (int i = 0, len = path.length(); i < len; i++) {
                char c = path.charAt(i);
                if (c == '/') {
                    sb.append(File.separator);
                } else {
                    sb.append(c);
                }
            }
            return sb.toString();
        } else {
            return path;
        }
    }

    public static void main(String[] args) {
        FileHelper.write("some txt (中文)", "e:\\txt.db");
    }
}
